package com.jiang.mapper;

import com.jiang.bean.Song;
import com.jiang.utils.DebugUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.ibatis.annotations.Param;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by dllo on 18/4/13.
 */
@Repository
public class NetSongDao {
    public List<Song> getKWSong(@Param(value = "songName") String songName) throws IOException {
        //建立List<Song>
        List<Song> songList = new ArrayList<Song>();
        //访问网址
        String url = "http://sou.kuwo.cn/ws/NSearch?type=all&catalog=yueku2016&key=" + songName;
        //建立连接
        Document document = Jsoup.connect(url)
                .userAgent("Mozilla/5.0(Macintosh;IntelMacOSX10.6;rv:2.0.1)Gecko/20100101Firefox/4.0.1")
                .get();

        //获取到ul下li标签
        Elements elements = document.select(".list > ul:nth-child(2) > li[class=\"clearfix\"]");


        //建立song实体类
        Song song;

        for (Element e : elements) {
            song = new Song();
            //获取歌名
            Element element = e.select(".m_name > a").first();
            String name = element.attr("title");
            DebugUtil.sout("歌名：" + name);
            song.setName(name);

            //获取酷我音乐歌曲id
            String songURL = element.attr("href");
            //用正则表达式过滤歌曲ID
            Pattern pattern = Pattern.compile("\\d+\\.?\\d*");
            Matcher matcher = pattern.matcher(songURL);
            if (matcher.find()) {
                String songId = matcher.group(0);
                String playURL = songId;
                DebugUtil.sout("播放地址：" + playURL);
                song.setUrl(playURL);
            }

            //获取专辑名
            element = e.select(".a_name > a").first();
            if (element != null) {
                String albumName = element.attr("title");
                DebugUtil.sout("专辑：" + albumName);
                song.setAlbum(albumName);
            }

            //获取歌手名
            element = e.select(".s_name > a").first();
            String author = element.attr("title");
            DebugUtil.sout("歌手：" + author);
            song.setAuthor(author);

            //将歌曲加入List
            songList.add(song);
        }
        return songList;
    }


    public void downloadMusic(@RequestParam(value = "songName") String songName,
                              @RequestParam(value = "downloadUrl") String downloadUrl,
                              HttpServletResponse response) throws IOException {
        //设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + songName + ".mp3");

        //创建一个浏览器
        HttpClient client = HttpClients.createDefault();
        //设置get请求
        HttpGet get = new HttpGet(downloadUrl);
        //定义流
        InputStream inputStream = null;
        //开始下载
        OutputStream os = response.getOutputStream();

        DebugUtil.sout("===>开始下载");
        //边读边写(下载过程)
        HttpResponse hr = client.execute(get);
        HttpEntity entity = hr.getEntity();
        inputStream = entity.getContent();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(buffer)) > 0) {
            os.write(buffer, 0, len);
        }
        DebugUtil.sout("===>下载完成");
        //关流
        os.close();
        inputStream.close();

    }
}
